package dianmobile.eistarandroid.ui.fragments;


import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.beans.MailEntity;
import dianmobile.eistarandroid.network.request.DelMailRequest;
import dianmobile.eistarandroid.network.request.MyMailsRequest;
import dianmobile.eistarandroid.network.request.RequestCallback;
import dianmobile.eistarandroid.network.request.RequestType;
import dianmobile.eistarandroid.ui.Adapter.InMailListAdapter;
import dianmobile.eistarandroid.ui.Adapter.OutMailListAdapter;
import dianmobile.eistarandroid.ui.activities.MailContentActivity;
import dianmobile.eistarandroid.ui.activities.MainActivity;
import dianmobile.eistarandroid.utils.ConstantsData;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

public class MyMailsFragment extends Fragment {

    private LayoutInflater mInflater;

    private List<MailEntity> inMailListData = new ArrayList<>();
    private List<MailEntity> outMailListData = new ArrayList<>();
    private ZrcListView inMailList;
    private ZrcListView outMailList;
    private InMailListAdapter inMailListAdapter;
    private OutMailListAdapter outMailListAdapter;

    private View viewHolder;
    private View viewMailInBox;
    private View viewMailOutBox;
    private List<View> viewList = new ArrayList<>();

    private TextView tvMailInBox;
    private TextView tvMailOutBox;
    private ImageView ivMailInBox;
    private ImageView ivMailOutBox;
    private ViewPager vpMail;

    private final static String IN_BOX = "InBox";
    private final static String OUT_BOX = "OutBox";
    private String selectState = IN_BOX;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mInflater = inflater;
        if (viewHolder == null) {
            viewHolder = inflater.inflate(R.layout.fragment_my_mails, container, false);
        }
        return viewHolder;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    /**
     * set the listView on ViewInBox
     */
    private void setViewMailInBoxList() {


        inMailListAdapter = new InMailListAdapter(getActivity(), inMailListData);
        inMailList.setAdapter(inMailListAdapter);
        refresh(IN_BOX);
        inMailList.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                inMailListData.get(position).setIsRead(true);
                inMailListAdapter.notifyDataSetChanged();
                Intent intent = new Intent(getActivity(), MailContentActivity.class);
                intent.putExtra("file", inMailListData.get(position).getFileName());
                intent.putExtra("num", Integer.toString(inMailListData.size() - position - 1));
                //intent.putExtra("backup", "0");
                intent.putExtra("userID", inMailListData.get(position).getUserID());
                intent.putExtra("mailTitle", inMailListData.get(position).getMailTitle());
                intent.putExtra("time", inMailListData.get(position).getSendTime());
                getActivity().startActivity(intent);
            }
        });
        inMailList.setOnItemLongClickListener(new ZrcListView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(ZrcListView parent, View view, int position, long id) {
                deleteDialog(inMailListData.get(position), IN_BOX);
                return true;
            }
        });
    }

    /**
     * set the listView on ViewOutBox
     */
    private void setViewMailOutBoxList() {

        outMailListAdapter = new OutMailListAdapter(getActivity(), outMailListData);
        outMailList.setAdapter(outMailListAdapter);
        refresh(OUT_BOX);
        outMailList.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), MailContentActivity.class);
                intent.putExtra("file", outMailListData.get(position).getFileName());
                intent.putExtra("num", Integer.toString(outMailListData.size() - position));
                intent.putExtra("backup", "1");
                intent.putExtra("userID", outMailListData.get(position).getUserID());
                intent.putExtra("mailTitle", outMailListData.get(position).getMailTitle());
                intent.putExtra("time", outMailListData.get(position).getSendTime());
                getActivity().startActivity(intent);
            }
        });

        outMailList.setOnItemLongClickListener(new ZrcListView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(ZrcListView parent, View view, int position, long id) {
                deleteDialog(outMailListData.get(position), OUT_BOX);
                return true;
            }
        });

    }

    private PagerAdapter viewPageAdapter = new PagerAdapter() {
        @Override
        public int getCount() {
            return viewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(viewList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(viewList.get(position), 0);
            return viewList.get(position);
        }
    };

    private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            switch (position){
                case 0:
                    MainActivity.slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
                    selectState = IN_BOX;
                    tvMailInBox.setAlpha((float) 1);
                    ivMailInBox.setVisibility(View.VISIBLE);
                    tvMailOutBox.setAlpha((float) 0.54);
                    ivMailOutBox.setVisibility(View.INVISIBLE);
                    break;
                case 1:
                    MainActivity.slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
                    selectState = OUT_BOX;
                    tvMailOutBox.setAlpha((float) 1);
                    ivMailOutBox.setVisibility(View.VISIBLE);
                    tvMailInBox.setAlpha((float) 0.54);
                    ivMailInBox.setVisibility(View.INVISIBLE);
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private void initView() {
        tvMailInBox = (TextView)viewHolder.findViewById(R.id.tv_in_mail_box);
        tvMailOutBox = (TextView)viewHolder.findViewById(R.id.tv_out_mail_box);
        ivMailInBox = (ImageView)viewHolder.findViewById(R.id.iv_in_mail_box);
        ivMailOutBox = (ImageView)viewHolder.findViewById(R.id.iv_out_mail_box);
        tvMailInBox.setOnClickListener(titleButtonListener);
        tvMailOutBox.setOnClickListener(titleButtonListener);

        vpMail = (ViewPager)viewHolder.findViewById(R.id.vp_mail_box);
        viewMailInBox = mInflater.inflate(R.layout.view_in_mail_box_list, null);
        viewMailOutBox = mInflater.inflate(R.layout.view_out_mail_box_list, null);


        inMailList = (ZrcListView)viewMailInBox.findViewById(R.id.lv_in_mail_box);
        outMailList = (ZrcListView)viewMailOutBox.findViewById(R.id.lv_out_mail_box);
        setPullToRefresh();
        setViewMailInBoxList();
        setViewMailOutBoxList();

        viewList.add(viewMailInBox);
        viewList.add(viewMailOutBox);
        vpMail.setAdapter(viewPageAdapter);
        vpMail.setOnPageChangeListener(pageChangeListener);
    }

    private View.OnClickListener titleButtonListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.tv_in_mail_box:
                    if (selectState.equals(OUT_BOX)) {
                        selectState = IN_BOX;
                        tvMailInBox.setAlpha((float)1);
                        ivMailInBox.setVisibility(View.VISIBLE);
                        tvMailOutBox.setAlpha((float) 0.54);
                        ivMailOutBox.setVisibility(View.INVISIBLE);
                        vpMail.setCurrentItem(0);
                    }
                    break;
                case R.id.tv_out_mail_box:
                    if (selectState.equals(IN_BOX)) {
                        selectState = OUT_BOX;
                        tvMailOutBox.setAlpha((float)1);
                        ivMailOutBox.setVisibility(View.VISIBLE);
                        tvMailInBox.setAlpha((float)0.54);
                        ivMailInBox.setVisibility(View.INVISIBLE);
                        vpMail.setCurrentItem(1);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * config the pull-to-refresh and load more at end
     */
    private void setPullToRefresh() {
        // 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(getActivity());
        header.setTextColor(0xff0066aa);
        header.setCircleColor(0xff33bbee);
        inMailList.setHeadable(header);
        outMailList.setHeadable(header);

        // 下拉刷新事件回调
        inMailList.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                refresh(IN_BOX);
            }
        });
        outMailList.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                refresh(OUT_BOX);
            }
        });
    }

    private void refresh(String boxName) {
        switch (boxName) {
            case IN_BOX:
                MyMailsRequest.execute(getActivity(), RequestType.INBOX_MAIL, new RequestCallback() {
                    @Override
                    public void onResult(Map<String, Object> result, String error) {
                        if (error == null) {
                            inMailListData.clear();
                            inMailListData.addAll((List<MailEntity>)result.get(ConstantsData.RESULT_DATA));
                            inMailListAdapter.notifyDataSetChanged();
                            inMailList.setRefreshSuccess();
                        } else {
                            inMailList.setRefreshFail("网络错误");
                        }
                    }
                });
                break;
            case OUT_BOX:
                MyMailsRequest.execute(getActivity(), RequestType.OUTBOX_MAIL, new RequestCallback() {
                    @Override
                    public void onResult(Map<String, Object> result, String error) {
                        if (error == null) {
                            outMailListData.clear();
                            outMailListData.addAll((List<MailEntity>)result.get(ConstantsData.RESULT_DATA));
                            outMailListAdapter.notifyDataSetChanged();
                            outMailList.setRefreshSuccess();
                        } else {
                            outMailList.setRefreshFail("网络错误");
                        }
                    }
                });
                break;
            default:
                break;
        }
    }

    private void deleteDialog(final MailEntity item, final String box) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("提示");
        builder.setMessage("确定删除吗");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, int which) {

                Map<String, String> params = new HashMap<>();
                params.put("file", item.getFileName());
                if(box.equals(IN_BOX)) {
                    params.put("backup", "0");
                } else if(box.equals(OUT_BOX)) {
                    params.put("backup", "1");
                }

                DelMailRequest.execute(getActivity(), RequestType.DEL_MAIL, params, new RequestCallback() {
                    @Override
                    public void onResult(Map<String, Object> result, String error) {
                        dialog.dismiss();
                        if (error == null) {
                            if (result.containsKey(ConstantsData.ERROR_RESULT)) {
                                Toast.makeText(getActivity(), (String) result.get(ConstantsData.ERROR_RESULT), Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(), "成功删除", Toast.LENGTH_SHORT).show();

                                if(box.equals(IN_BOX)) {
                                    inMailListData.remove(item);
                                    inMailListAdapter.notifyDataSetChanged();
                                } else if(box.equals(OUT_BOX)) {
                                    outMailListData.remove(item);
                                    outMailListAdapter.notifyDataSetChanged();
                                }
                            }
                        } else {
                            Toast.makeText(getActivity(), "网络错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
}
